package com.company.learnjpa.view;

import com.company.learnjpa.util.Helper;
import jakarta.enterprise.context.RequestScoped;
import jakarta.faces.context.FacesContext;
import jakarta.inject.Inject;
import jakarta.inject.Named;
import jakarta.security.enterprise.AuthenticationStatus;
import static jakarta.security.enterprise.AuthenticationStatus.SEND_CONTINUE;
import static jakarta.security.enterprise.AuthenticationStatus.SUCCESS;
import jakarta.security.enterprise.SecurityContext;
import jakarta.security.enterprise.authentication.mechanism.http.AuthenticationParameters;
import jakarta.security.enterprise.credential.Password;
import jakarta.security.enterprise.credential.UsernamePasswordCredential;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.validation.constraints.NotNull;
import jakarta.validation.constraints.Size;

/**
 *
 * @author xiaolei
 */
@Named(value = "loginBacking")
@RequestScoped
public class LoginBacking {

    @Inject
    private SecurityContext securityContext;
    @Inject
    private FacesContext facesContext;

    @NotNull
    @Size(min = 3, max = 20)
    private String username;

    @NotNull
    @Size(min = 5, max = 50)
    private String password;

    public void login() {
        System.out.println("--->" + username + "," + password);
        HttpServletRequest request = (HttpServletRequest) facesContext.getExternalContext().getRequest();
        HttpServletResponse response = (HttpServletResponse) facesContext.getExternalContext().getResponse();
        UsernamePasswordCredential credential = new UsernamePasswordCredential(username, new Password(password));

        AuthenticationStatus status
                = securityContext.authenticate(request, response,
                        AuthenticationParameters.withParams().credential(credential));

        System.out.println("---->" + status);

        switch (status) {
            case SEND_CONTINUE:
                facesContext.responseComplete();
                break;
            case SEND_FAILURE:
                Helper.addErrorMessage("Error", "用户名或密码错误");
                break;
            case SUCCESS:
                Helper.redirect("/blog/home.xhtml");
                break;
            default:
        }
    }

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

}
